/**
 * ResizeObserver错误处理工具
 * 解决Element Plus组件中的ResizeObserver循环错误
 */

// 全局ResizeObserver错误处理
export function setupResizeObserverFix() {
  if (typeof window === 'undefined') return

  // 保存原始的console.error
  const originalError = console.error
  const originalWarn = console.warn

  // 重写console.error，过滤ResizeObserver错误
  console.error = (...args) => {
    const message = args[0]
    if (typeof message === 'string' && 
        (message.includes('ResizeObserver') || 
         message.includes('ResizeObserver loop completed'))) {
      // 忽略ResizeObserver相关错误
      return
    }
    originalError.apply(console, args)
  }

  // 重写console.warn，过滤ResizeObserver警告
  console.warn = (...args) => {
    const message = args[0]
    if (typeof message === 'string' && 
        (message.includes('ResizeObserver') || 
         message.includes('ResizeObserver loop completed'))) {
      // 忽略ResizeObserver相关警告
      return
    }
    originalWarn.apply(console, args)
  }

  // 添加全局错误处理器
  window.addEventListener('error', (event) => {
    if (event.message && event.message.includes('ResizeObserver')) {
      event.preventDefault()
      return false
    }
  })

  // 添加未处理的Promise拒绝处理器
  window.addEventListener('unhandledrejection', (event) => {
    if (event.reason && event.reason.message && 
        event.reason.message.includes('ResizeObserver')) {
      event.preventDefault()
      return false
    }
  })
}

// 安全的异步操作包装器
export function safeAsyncOperation(operation, delay = 100) {
  return new Promise((resolve, reject) => {
    try {
      setTimeout(() => {
        try {
          const result = operation()
          resolve(result)
        } catch (error) {
          if (error.message && error.message.includes('ResizeObserver')) {
            // 忽略ResizeObserver错误，继续执行
            resolve()
          } else {
            reject(error)
          }
        }
      }, delay)
    } catch (error) {
      reject(error)
    }
  })
}

// 组件重置工具
export function safeReset(form, callback, delay = 150) {
  return safeAsyncOperation(() => {
    // 重置表单
    Object.keys(form).forEach(key => {
      if (key.includes('date')) {
        form[key] = ''
      } else {
        form[key] = null
      }
    })
    
    // 执行回调
    if (typeof callback === 'function') {
      callback()
    }
  }, delay)
} 